package com.hnkywl.sts.service.cwgl;

import com.google.gson.Gson;
import com.hnkywl.sts.dao.cwgl.KhzhsfmxDao;
import com.hnkywl.sts.dao.cwgl.KmdmDao;
import com.hnkywl.sts.dao.cwgl.TxcdDao;
import com.hnkywl.sts.dao.cwgl.kmys.CykmdmysDao;
import com.hnkywl.sts.dao.organ.GsjgDao;
import com.hnkywl.sts.dao.zjgl.PjdrDao;
import com.hnkywl.sts.entity.cggl.Jsd;
import com.hnkywl.sts.entity.cwgl.Khzhsfmx;
import com.hnkywl.sts.entity.cwgl.Kmdm;
import com.hnkywl.sts.entity.cwgl.Qtpz;
import com.hnkywl.sts.entity.cwgl.VoucherItemData;
import com.hnkywl.sts.entity.sfgl.Sfk;
import com.hnkywl.sts.entity.sys.Yg;
import com.hnkywl.sts.entity.zjgl.Pj;
import com.hnkywl.sts.entity.zjgl.Pjdr;
import com.hnkywl.sts.service.organ.KhhService;
import com.hnkywl.sts.service.sfgl.FkshService;
import com.hnkywl.sts.service.sfgl.SkshService;
import com.hnkywl.sts.service.sys.YgService;
import com.hnkywl.sts.service.zjgl.PjglService;
import com.hnkywl.sts.util.BaseUtils;
import net.ruixin.orm.hibernate.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Array;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * User: Administrator
 * Date: 13-5-14
 * Time: 上午11:26
 * To change this template use File | Settings | File Templates.
 */
@Service
public class TxcdService {
   private TxcdDao txcdDao;
    private PjglService pjglService;
    private GsjgDao gsjgDao;
    private PjdrDao pjdrDao;
    private KhzhsfmxDao khzhsfmxDao;
    private KmdmDao kmdmDao;
    @Transactional
    public String findAllTxcd(Long gsId,String gsMc,Integer txcdZt,Integer  voucherNum,String czr,Long djh,Integer pjlx,String rzyh,int pageNo, int pageSize) {
        Long nbgsIds = null;
        if(gsId !=null && gsMc.equals(gsjgDao.get(gsId).getJc())){
            nbgsIds = gsId;
        }
            Page<Pjdr> txcdPage = this.txcdDao.findAllTxcd(nbgsIds,gsMc,txcdZt,voucherNum,czr,djh,pjlx,rzyh,pageNo, pageSize);
            List<Pjdr> txcdList = txcdPage.getResult() == null ? new ArrayList<Pjdr>() : txcdPage.getResult();
            if(txcdList.size()>0){
                txcdList = getCzztByPj(txcdList);
            }
            String txcdJson = BaseUtils.fetchCollectionToJson(txcdList, "id", "nbgs.jc", "status", "pjlx", "dqje","czzt","createUser.xm", "rzyh.qc","dateCreated", "voucherNum","bz","pjhm");
            return "{\"total\":" + txcdPage.getTotalCount() + ",\"rows\":[" + txcdJson + "]}";
    }

    public List<Pjdr> getCzztByPj(List<Pjdr> pjdrList){
        for(Pjdr pjdr:pjdrList){
            String czzt = "";
            String pjhm = "";
            if(pjdr.getPjList().size()>0){
                for(Pj pj :pjdr.getPjList()){
                       pjhm += pj.getPjhm()+",";
                }
                pjhm = pjhm.substring(0,pjhm.length()-1);
            }
            if(pjdr.getInsertFlag()==1 && pjdr.getDeleteFlag()==1){
                czzt = "wdr";
            }else if(pjdr.getInsertFlag()==1 && pjdr.getDeleteFlag()==3){
                czzt = "sccg";
            }else if(pjdr.getInsertFlag()==3 && pjdr.getDeleteFlag()==1){
                czzt = "drcg";
            }else if(pjdr.getInsertFlag()==2 && pjdr.getDeleteFlag()==1 ||pjdr.getInsertFlag()==2 && pjdr.getDeleteFlag()==3 ){
                czzt = "drsb";
            }else if(pjdr.getInsertFlag()==3 && pjdr.getDeleteFlag()==2){
                czzt = "scsb";
            }else{
                czzt = "null";
            }
            pjdr.setCzzt(czzt);
            pjdr.setPjhm(pjhm);
        }
        return pjdrList;
    }

    @Transactional
    public Map getRevokeInfo(Long id) {
        Map<String, Object> revokeInfo = new HashMap<String, Object>();
        Pjdr result = pjdrDao.get(id);
        if (result == null) {
            throw new RuntimeException("未获取凭证信息!");
        }
        DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat simpleDateFormat3 = new SimpleDateFormat("MM");
        revokeInfo.put("id", result.getUuid());//凭证ID
        revokeInfo.put("vchrid", result.getVoucherId());//凭证ID
        revokeInfo.put("unitcode", result.getNbgs().getJiuqiUnitCode());//单位代码
        revokeInfo.put("vchrtypecode", "记");//会计年度
        revokeInfo.put("acctyear", result.getAcctyear());//会计年度
        revokeInfo.put("acctperiod",simpleDateFormat3.format(result.getDrrq()));//会计年度
        revokeInfo.put("vchrnum", result.getVoucherNum());//凭证号

        return revokeInfo;
    }

//    @Transactional
//    public Map getVoucher(Long id, String uuid, List<VoucherItemData> voucherItemDataList) {
//        SimpleDateFormat simple = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
//        String systemDate =simple.format(new Date());
//        Pjdr pjdr = txcdDao.get(id);
//        Map<String, Object> result = new HashMap<String, Object>();
//        List<VoucherItemData> list = this.txcdDao.getVoucher(pjdr);
//        DecimalFormat df = new DecimalFormat("#.##");
//        //凭证分录信息
//        List<Map> items = new ArrayList<Map>();
//        int order = 1;
//        for (VoucherItemData item : list) {
//            Map<String, Object> voucherItem = new HashMap<String, Object>();
//            voucherItem.put("id", order);//唯一标识
//            voucherItem.put("vchrid", uuid);//凭证主表ID
//            voucherItem.put("itemorder", order);//分录编号
//            voucherItem.put("subjectcode", item.getKmdm() != null && item.getKmdm() != null ? item.getKmdm() : "");//科目代码
//            voucherItem.put("subjectname", item.getKmdm() != null && item.getKmmc() != null ? item.getKmmc() : "");//科目名称
//            voucherItem.put("debit", item.getJf() != null ? df.format(item.getJf()) : 0.00);//借方金额
//            voucherItem.put("credit", item.getDf() != null ? df.format(item.getDf()) : 0.00);//贷方金额
//            voucherItem.put("qty", item.getQty() != null ? item.getQty() : 0);//数量
//            voucherItem.put("price", 0);//单价
//            voucherItem.put("currencycode", "CNY");//货币代码
//            voucherItem.put("exchrate", 1.000000);//汇率
//            voucherItem.put("orgnd", item.getJf() != null ? df.format(item.getJf()) : 0.00);//借方原币
//            voucherItem.put("orgnc", item.getDf() != null ? df.format(item.getDf()) : 0.00);//贷方原币
//            voucherItem.put("settlementcode", "");//结算方式代码
//            voucherItem.put("settlementno", "");//结算号
//            voucherItem.put("bizdate", simple.format(new Date()));//业务日期
//            voucherItem.put("digest", item.getZy() != null ? item.getZy() : "");//摘要
//            voucherItem.put("bizno", "");//业务号
//            voucherItem.put("suppliername", item.getSupplierName() != null ? item.getSupplierName() : "");//供应商名称
//            voucherItem.put("suppliercode", item.getSupplierCode() != null ? item.getSupplierCode() : "");//供应商代码
//            voucherItem.put("departmentname", item.getDeptName() != null ? item.getDeptName() : "");//部门名称
//            voucherItem.put("departmentcode", item.getDeptCode() != null ? item.getDeptCode() : "");//部门代码
//            voucherItem.put("customername", item.getCustomerName() != null ? item.getCustomerName() : "");//客户名称
//            voucherItem.put("customercode", item.getCustomerCode() != null ? item.getCustomerCode() : "");//客户代码
//            voucherItem.put("staffname", item.getUserName() != null ? item.getUserName() : "");//职员名称
//            voucherItem.put("staffcode", item.getUserCode() != null ? item.getUserCode() : "");//职员代码
//            items.add(voucherItem);
//            order++;
//        }
//        result.put("items", items);
//        return result;
//    }

    @Transactional
    public String findQtpzfl(Long id) {
        Pjdr pjdr = this.pjdrDao.get(id);
        List<VoucherItemData> list = this.txcdDao.getVoucher(pjdr);
        List<Map> txcdJson = new ArrayList<Map>();
        for (int i =0;i<list.size() ;  i++){
            VoucherItemData voucherItemData = list.get(i);
            Map<String, Object> voucherItem = new HashMap<String, Object>();
            voucherItem.put("zy",voucherItemData.getZy());
            voucherItem.put("km",voucherItemData.getKmmc());
            voucherItem.put("df",voucherItemData.getDf()==null?0d:voucherItemData.getDf());
            voucherItem.put("jf",voucherItemData.getJf()==null?0d:voucherItemData.getJf());
            txcdJson.add(voucherItem);
        }
        return new Gson().toJson(txcdJson);
    }

    @Transactional
    public Map getVoucherMaster(Long id, Integer attachment, String uuid, String year, String mouth, Yg yg) {
        SimpleDateFormat simple = new SimpleDateFormat("yyyy-MM-dd");
        String systemDate =simple.format(new Date());
        Map<String, Object> voucherMaster = new HashMap<String, Object>();
        Pjdr result = pjdrDao.get(id);
        voucherMaster.put("id", uuid);
        voucherMaster.put("vchrtypecode", "记");//凭证类别
        voucherMaster.put("acctyear", year != null ? year : "");//会计年度
        voucherMaster.put("acctperiod", mouth != null ? mouth : "");//会计期间
        voucherMaster.put("createdate", systemDate);//凭证日期
        voucherMaster.put("unitcode", result.getNbgs() != null && result.getNbgs().getJiuqiUnitCode() != null ? result.getNbgs().getJiuqiUnitCode() : "");//组织机构代码
        voucherMaster.put("acctbookcode", "01");//账薄标识
        voucherMaster.put("createuser", yg.getXm());//制单人
        voucherMaster.put("attachment", attachment);//附件张数
        voucherMaster.put("memo", "");//备注
        voucherMaster.put("companyId", result.getNbgs().getId());//公司ID
        return voucherMaster;
    }

    /**
     * 获取U8凭证分录信息
     *
     * @param id
     * @param uuid
     * @return
     */
    @Transactional
    public Map getU8VoucherItems(Long id, String uuid,List<VoucherItemData> voucherItemDataList,Date documentDate) {
        SimpleDateFormat simple = new SimpleDateFormat("yyyy-MM-dd");
        String systemDate =simple.format(new Date());
        Pjdr pjdr = this.txcdDao.get(id);
        Map<String, Object> result = new HashMap<String, Object>();
        List<VoucherItemData> list = this.txcdDao.getVoucher(pjdr);
        DecimalFormat df = new DecimalFormat("#.##");
        //凭证分录信息
        List<Map> items = new ArrayList<Map>();
        int order = 1;
        for(VoucherItemData m : list){
            Map<String, Object> voucherItem = new HashMap<String, Object>();
            //voucherItem.put("id", order);//唯一标识
            //voucherItem.put("vchrid", uuid);//凭证主表ID
            voucherItem.put("entry_id", order);//分录编号
            voucherItem.put("account_code", m.getKmdm() != null ? m.getKmdm() : "");//科目代码
//                voucherItem.put("subjectname", item.getKmdm() != null && item.getKmmc() != null ? item.getKmmc() : "");//科目名称
            voucherItem.put("natural_debit_currency", m.getJf() != null ? df.format(m.getJf()) : "0.00");//借方金额
            voucherItem.put("natural_credit_currency", m.getDf()!= null ? df.format(m.getDf()) : "0.00");//贷方金额
//                voucherItem.put("qty", item.getSl() != null ? item.getSl() : 0);//数量
            voucherItem.put("unit_price", "0");//单价,在科目有数量核算时，填写此项
            voucherItem.put("debit_quantity", "0");//借方数量,在科目有数量核算时，填写此项
            voucherItem.put("credit_quantity", "0");//贷方数量,在科目有数量核算时，填写此项
            voucherItem.put("currency", "CNY");//货币代码
            voucherItem.put("exchange_rate2", "1.000000");//汇率
//                voucherItem.put("orgnd", item.getJfje() != null ? df.format(item.getJfje()) : "0.00");//借方原币
//                voucherItem.put("orgnc", item.getDfje() != null ? df.format(item.getDfje()) : "0.00");//贷方原币
            voucherItem.put("settlement", "");//结算方式,在科目是银行或往来时，可以填写此项
            voucherItem.put("document_id", "");//票据号，在科目是银行或往来时，可以填写此项
            voucherItem.put("document_date",systemDate);//票据日期，在科目是银行或往来时，可以填写此项
            voucherItem.put("abstract", m.getZy() != null ? m.getZy() : "");//摘要
//                voucherItem.put("bizno", "");//业务号
            Map<String, String> fzhsMap = new HashMap<String, String>();
            Map<String, Map> xjllxmMap = new HashMap<String, Map>();
            fzhsMap =  this.findFzhsByMap(pjdr,m,fzhsMap,xjllxmMap);
            voucherItem.put("auxiliary_accounting", fzhsMap);
            voucherItem.put("cash_flow", xjllxmMap);
            items.add(voucherItem);
            order++;
        }
        result.put("items", items);
        return result;
    }

    @Transactional
    public void pjdrChangeDrrq(Long pjdrId,Date date){
        Pjdr pjdr = this.txcdDao.get(pjdrId);
        pjdr.setDrrq(date);
        pjdrDao.save(pjdr);
    }



    private Map<String,String > findFzhsByMap(Pjdr pjdr, VoucherItemData voucherItemData,Map<String, String> fzhsMap, Map<String, Map> xjllxmMap){
        //1.更具公司还有代码查询科目代码
        Kmdm kmdm = kmdmDao.findKmdmDetailByGs(pjdr.getNbgs().getId(),voucherItemData.getKmdm());
        if(kmdm==null){
            kmdm = kmdmDao.findKmdmDetailByGs(YgService.getCurrentYgZgGsId(),voucherItemData.getKmdm());
        }
        //2.现金流量项目
        if(kmdm!=null&& kmdm.getXjllsx() !=null && !"".equals(kmdm.getXjllsx()) &&  kmdm.getXjllsx().equals("Y")){
            if(pjdr.getStatus()==2 ||pjdr.getStatus()==3){
                fzhsMap.put("item_id", "01");
            }else{
                fzhsMap.put("item_id", "04");
            }
            Map value = new HashMap<String, Double>();
            Double d = voucherItemData.getJf() != null ? voucherItemData.getJf():0.00 ;
            Double c = voucherItemData.getDf() != null ? voucherItemData.getDf():0.00;
            value.put("debit", d);
            value.put("credit", c);
            value.put("md", Math.abs(d - c));
            value.put("ccode", voucherItemData.getKmdm());
            if(pjdr.getStatus()==2 ||pjdr.getStatus()==3){
                xjllxmMap.put("01", value);
            }else{
                xjllxmMap.put("04", value);
            }
        }//3.其他项目
        else  if(kmdm !=null && kmdm.getTyfzhsmc()!=null && kmdm.getTyfzhsys() != null ){
            fzhsMap.put("item_id",kmdm.getTyfzhsys().getCode() );
        }
        else{
            if( voucherItemData.getCustomerCode()!=null && !voucherItemData.getCustomerCode().toString().equals("")){
                fzhsMap.put("cust_id",voucherItemData.getCustomerCode());
            }
            if(voucherItemData.getSupplierCode() !=null && !voucherItemData.getSupplierCode().toString().equals("")){
                fzhsMap.put("supplier_id",voucherItemData.getSupplierCode());
                fzhsMap.put("operator","-");
            }
            if(voucherItemData.getDeptCode() !=null && !voucherItemData.getDeptCode().toString().equals("")){
                fzhsMap.put("dept_id",voucherItemData.getDeptCode());
            }
        }
        return fzhsMap;
    }


    @Transactional
    public String revokeNote(Long txcdId) {
        String error = null;
        Pjdr pjdr = txcdDao.get(txcdId);
        //还原银行存款
        List<Khzhsfmx> khzhsfmxList = khzhsfmxDao.findKhzhsfmxByPjdr(pjdr.getId());
        if(khzhsfmxList.size()>0){
            for(Khzhsfmx khzhsfmx :khzhsfmxList){
                khzhsfmx.setDeleted(1);
                khzhsfmx.setLastUpdated(new Date());
                khzhsfmxDao.save(khzhsfmx);
            }
            pjdr.setDeleted(1);
            pjdrDao.save(pjdr);
        }
        try {
            if(pjdr.getStatus()==2){//取消贴现
                for(Pj p :pjdr.getPjList()){
                    this.pjglService.pjglQxtx(p);
                }
                pjdr.setDeleted(1);
                pjdrDao.save(pjdr);
            }

            if(pjdr.getStatus()==3){//取消托收
                    for(Pj p :pjdr.getPjList()){
                        this.pjglService.pjglQxts(p);
                    }
            }
            if(pjdr.getStatus()==4){//取消承兑
                for(Pj p :pjdr.getPjList()){
                    this.pjglService.pjglQxcd(p);
                }
                pjdr.setDeleted(1);
                pjdrDao.save(pjdr);
            }
        } catch (Exception e) {
            error = e.getMessage();
        }
        return error;
    }


    @Autowired
    public void setTxcdDao(TxcdDao txcdDao) {
        this.txcdDao = txcdDao;
    }
    @Autowired
    public void setPjglService(PjglService pjglService) {
        this.pjglService = pjglService;
    }

    @Autowired
    public void setGsjgDao(GsjgDao gsjgDao) {
        this.gsjgDao = gsjgDao;
    }

    @Autowired
    public void setPjdrDao(PjdrDao pjdrDao) {
        this.pjdrDao = pjdrDao;
    }
    @Autowired
    public void setKhzhsfmxDao(KhzhsfmxDao khzhsfmxDao) {
        this.khzhsfmxDao = khzhsfmxDao;
    }
    @Autowired
    public void setKmdmDao(KmdmDao kmdmDao) {
        this.kmdmDao = kmdmDao;
    }
}
